package org.kl.bf.web.basic;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.io.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.kl.bf.entity.basic.Attachment;
import org.kl.bf.entity.basic.ExcelImportTemp;
import org.kl.bf.entity.easyui.EasyuiUtils;
import org.kl.bf.service.ServiceException;
import org.kl.bf.service.basic.ExcelImportTempService;
import org.kl.bf.utils.KLServlets;
import org.kl.bf.web.base.BasicController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.MediaTypes;

@Controller
@RequestMapping(value = "/basic/excelImportTemp")
public class ExcelImportTempController extends BasicController {

	@Autowired
	private ExcelImportTempService excelImportTempService;

	@RequiresPermissions(value = "excelImportTemp:list")
	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "basic/excelImportTempList";
	}

	/**
	 * 获取数据
	 * 
	 * @param pageNumber
	 * @param pageSize
	 * @param sortType
	 * @param orderType
	 * @param model
	 * @param request
	 * @return
	 */
	@RequiresPermissions(value = "excelImportTemp:list")
	@RequestMapping(value = "dataGrid", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String dataGrid(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request) {
		try {
			Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
			Page<ExcelImportTemp> excelImportTemp = excelImportTempService.getPage(searchParams, pageNumber, pageSize, sortType, orderType);
			return EasyuiUtils.buildEasyuiGridJsonString(excelImportTemp.getContent(), (int) excelImportTemp.getTotalElements());
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("获取数据失败:" + e.getMessage(), false, null);
		}
	}

	/**
	 * 删除多条数据，级联删除
	 * 
	 * @param ids
	 * @return
	 */
	@RequiresPermissions(value = "excelImportTemp:delete")
	@RequestMapping(value = "multiDelete", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String multiDelete(@RequestParam(value = "ids", defaultValue = "") String ids) {
		String msg = "";
		try {
			msg = excelImportTempService.multiDelete(ids);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("删除失败:" + e.getMessage(), false, null);
		}
		return ajaxMsg("删除成功:" + msg, true, null);
	}

	/**
	 * 添加与更新
	 * 
	 * @param ExcelImportTemp
	 * @param request
	 * @return
	 */
	@RequiresPermissions(value = "excelImportTemp:update")
	@RequestMapping(value = "update", method = RequestMethod.POST, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String update(@Valid @ModelAttribute("excelImportTemp") ExcelImportTemp excelImportTemp, ServletRequest request) {
		try {
			excelImportTempService.save(excelImportTemp);
			return ajaxMsg("保存成功!", true, null);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("保存失败!", false, null);
		}
	}

	/**
	 * 文件下载
	 * 
	 * @author QJ
	 * @param response
	 * @param request
	 * @param realName
	 * @param name
	 */
	@RequestMapping("/download/{importTempNo}")
	public void download(HttpServletResponse response, HttpServletRequest request, @PathVariable("importTempNo") String importTempNo) {
		ExcelImportTemp importTemp = excelImportTempService.findByImportTempNo(importTempNo);
		if (importTemp == null) {
			throw new ServiceException("编号为" + importTempNo + "的Excel模板不存在");
		}
		if (importTemp.getAttachmentMaster().getAttachmentList().size() > 0) {
			OutputStream os = null;
			response.reset();
			Attachment a = importTemp.getAttachmentMaster().getAttachmentList().get(0);
			try {
				response.setHeader("Content-Disposition",
						(new StringBuilder("attachment; filename=")).append(new String(a.getFileName().getBytes("GBK"), "iso8859-1"))
								.toString());// 解决中文乱码问题
				response.setContentType("application/octet-stream; charset=utf-8");
				os = response.getOutputStream();
				os.write(FileUtils.readFileToByteArray(new File(a.getFilePath())));
				os.flush();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (os != null) {
					try {
						os.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void init(@RequestParam(value = "id", defaultValue = "-1") String id, Model model) {
		if (!id.equals("-1")) {
			model.addAttribute("excelImportTemp", excelImportTempService.getOne(id));
		}
	}
}
